<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { filterOutImages, filterImageFiles, downloadAndOpenFile } from '@/utils/index.js'
import { config } from '@/common/config.js'
import { getToken } from '@/utils/index.js'
import { getFileInfoApi, deleteFileInfoApi } from '@/apis/globalSbmitForm.js'

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  action: {
    type: String,
    required: true
  }
})
// 获取附件信息
const fileData = ref([])
const getFileData = async (id) => {
  const res = await getFileInfoApi({ pkid: id })
  console.log("1231", res)
  fileData.value = res.rows
}
// 监听id变化，确保只有在id存在时才请求数据
watch(() => props.id, (newId) => {
  if (newId) {
    getFileData(newId)
  } else {
    // 当id为空时清空数据
    fileData.value = []
  }
}, { immediate: true })
// 获取图片
const imgList = computed(() => {
  const list = filterImageFiles(fileData.value)
  if (!list.length) return []
  return list.map(item => {
    return {
      ...item,
      filename: config.baseUrl + item.filename
    }
  })
})
// 获取文件
const fileList = computed(() => {
  return filterOutImages(fileData.value)
})

const fileShow = ref(false)
// 选择图片
const handlerImage = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['album', 'camera'],
    success: (success) => {
      upload(success.tempFilePaths[0])
    },
  })
}
// 选择文件
const handlerFile = () => {
  uni.chooseMessageFile({
    count: 1,
    type: 'file',
    success: (success) => {
      upload(success.tempFiles[0].path)
    },
  })
}
const upload = (tempFilePath) => {
  uni.uploadFile({
    url: props.action,
    filePath: tempFilePath,
    name: 'file',
    header: {
      'Authorization': 'Bearer ' + getToken()
    },
    success (res) {
      const data = JSON.parse(res.data)
      if (data.code == 200) {
        fileData.value = data.attachList
        fileShow.value = false
        uni.$u.toast("上传成功")
      }
    },
    fail (e) {
      console.log("上传失败", e)
      uni.$u.toast(e.errMsg || "上传失败")
    }
  })
}

// 删除附件
const deleteImg = async (id) => {
  try {
    const res = await deleteFileInfoApi(id)
    uni.$u.toast("删除成功")
    fileData.value = fileData.value.filter(item => item.id != id)
  } catch (e) {
    console.log('e', e)
    uni.$u.toast("删除失败")
  }
}

// 预览图片
const previewImage = (current) => {
  // 获取所有图片的URL数组
  const urls = imgList.value.map(item => item.filename)

  uni.previewImage({
    current,
    urls,
    success: function (res) {
      console.log('图片预览成功', res)
    },
    fail: function (error) {
      console.log('图片预览失败', error)
      uni.$u.toast('图片预览失败')
    }
  })
}

// 下载附件
const handlerDownload = async filename => {
  try {
    await downloadAndOpenFile(filename, {
      header: {
        'myid': String(1)
      }
    });
  } catch (error) {
    console.error('下载文件处理失败:', error);
    // 错误处理已在downloadAndOpenFile函数内部完成
  }
}
</script>


<template>
  <div class="container">
    <u-form-item label="附件:" label-width="100">
      <view class="img_list flex">
        <view v-for="item in imgList" :key="item.id" class="flex img_item">
          <image :src="item.filename" @click="previewImage(item.filename)" mode="scaleToFill" />
          <view class="delete_img flex" @click="deleteImg(item.id)">x</view>
        </view>
        <view class="file_container flex" v-if="imgList.length <= 3" @click="fileShow = true">+</view>
      </view>
    </u-form-item>
    <view class="file_list">
      <view v-for="(item, index) in fileList" :key="item.id">
        <view class="flex_sb" style="margin-bottom: 10rpx;">
          <view class="xh">({{ index + 1 }})</view>
          <view class="originalname overflow_1">{{ item.originalname }}</view>
          <view class="download flex_sb">
            <view class="flex download_btn delete_btn" @click="deleteImg(item.id)">删除</view>
            <view class="flex download_btn " @click="handlerDownload(item.filename)">下载</view>
          </view>
        </view>
      </view>
    </view>
  </div>
  <!-- 选择附属文件上传 -->
  <u-popup v-model="fileShow" mode="bottom">
    <view class="popup_more_list flex upload_img" @click="handlerImage">上传图片</view>
    <view class="popup_more_list flex" @click="handlerFile">上传文件</view>
  </u-popup>
</template>


<style scoped lang="scss">
.popup_more_list {
  height: 100rpx;
  width: 750rpx;

  .upload_img {
    border-top: 2px solid #eee;
  }
}

.img_list {
  justify-content: flex-start;

  .img_item {
    position: relative;
    width: 100rpx;
    height: 100rpx;
    margin-right: 20rpx;
  }

  .delete_img {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 40rpx;
    height: 40rpx;
    background: #fa3d3c;
    border-radius: 50%;
    color: #fff;
    font-size: 22rpx;
  }

  image {
    width: 100%;
    height: 100%;
  }

  .file_container {
    width: 100rpx;
    height: 100rpx;
    background: #f4f5f6;
    font-size: 50rpx;
    color: #999;
  }
}


.file_list {
  font-size: 28rpx;

  .xh {
    width: 50rpx;
  }

  .originalname {
    flex: 1;
  }

  .download {
    width: 230rpx;
  }

  .download_btn {
    padding: 10rpx 20rpx;
    background: #dbf1e1;
    border: 1rpx solid #a5e3c2;
    color: #2ecdbf;
  }

  .delete_btn {
    color: #fa3d3c;
    background: #fef0f0;
    border: 1px solid #fb9898;
  }
}
</style>
